package edu.hm.vss.pingpong;

import java.net.*; 
import java.io.*;

public class USocketsServer {
   USocketsServer(){
	   String ping = "ping";
	   String pong = "pong";
	   byte[] msg = new byte[1024];
	   try {
	
		   DatagramSocket ssock    = new DatagramSocket(); 
		   String         hostname = "" + ssock.getInetAddress();
		   int            portnum  = ssock.getLocalPort();
		   System.out.println("UDP-Server: Verbindungsdaten: Addresse = " + hostname + ", Port = " + portnum);
		   while(true){
			   // erzeuge Datagramm-Puffer und empfange Request vom Client
			   DatagramPacket request = new DatagramPacket(msg, msg.length);
			   ssock.receive(request);
			   String recvMsg = new String(msg);
			   if(recvMsg==ping) {
				   System.out.println("got PING");
				   msg = pong.getBytes();
				   request.setData(msg);
				// erzeuge Antwort als Datagramm-Nachricht und sende diese
				   DatagramPacket reply = new DatagramPacket(request.getData(),
						   request.getLength(), request.getAddress(), request.getPort());
				   ssock.send(reply);	
			   }
			   else {
				   System.out.println("got an error");
			   }
						   
		   }
	   }
	   catch (Exception e) {
      // hier entsprechendes Exception-Handling 
	   } 
   } 
 }